﻿using Consul;
using ELF.Modules;
using Microsoft.Extensions.Options;


namespace ELF.Consul
{
    public class ELFConsulModule : IModule
    {
        public async Task ConfigureServicesAsync(IHostApplicationBuilder builder)
        {
            builder.Services.Configure<ConsulOptions>(builder.Configuration.GetSection(nameof(ConsulOptions)));
            var options = builder.Configuration.GetSection(nameof(ConsulOptions)).Get<ConsulOptions>();
            if (options != null)
            {
                // 添加Consul客户端
                builder.Services.AddSingleton<IConsulClient>(sp => new ConsulClient(config =>
                {
                    var consulAddress = options.Address;
                    config.Address = new Uri(consulAddress);
                }));
                // 注册Consul托管服务
                builder.Services.AddHostedService<ConsulHostedService>();
                // 添加健康检查端点
                builder.Services.AddHealthChecks();
            }


            await Task.CompletedTask;
        }

        public async Task InitializeAsync(IApplicationBuilder app)
        {
            var options = app.ApplicationServices.GetRequiredService<IOptions<ConsulOptions>>().Value;
            if (options != null)
            {
                app.UseHealthChecks(path: options.HealthCheckEndpoint);
            }
            await Task.CompletedTask;
        }
    }
}
